package com.yunshan.welfare.service.impl;

import com.yunshan.common.utils.DateUtils;
import com.yunshan.common.utils.SecurityUtils;
import com.yunshan.common.utils.StringUtils;
import com.yunshan.member.domain.MemberSubCardInfo;
import com.yunshan.member.domain.MemberUserInfo;
import com.yunshan.member.service.IMemberSubCardInfoService;
import com.yunshan.member.service.IMemberUserInfoService;
import com.yunshan.mp.domain.ResultServe;
import com.yunshan.welfare.domain.WelfareGift;
import com.yunshan.welfare.domain.WelfareGiftContent;
import com.yunshan.welfare.domain.WelfareGiftRecord;
import com.yunshan.welfare.mapper.WelfareGiftRecordMapper;
import com.yunshan.welfare.service.IWelfareGiftContentService;
import com.yunshan.welfare.service.IWelfareGiftRecordService;
import com.yunshan.welfare.service.IWelfareGiftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 礼包发放详情Service业务层处理
 *
 * @author yunshan
 * @date 2025-01-20
 */
@Service
public class WelfareGiftRecordServiceImpl implements IWelfareGiftRecordService
{
    @Autowired
    private WelfareGiftRecordMapper welfareGiftRecordMapper;
    @Autowired
    private IMemberUserInfoService memberUserInfoService;
    @Autowired
    private IWelfareGiftService welfareGiftService;
    @Autowired
    private IWelfareGiftContentService welfareGiftContentService;
    @Autowired
    private IMemberSubCardInfoService memberSubCardInfoService;

    /**
     * 查询礼包发放详情
     *
     * @param id 礼包发放详情主键
     * @return 礼包发放详情
     */
    @Override
    public WelfareGiftRecord selectWelfareGiftRecordById(Long id)
    {
        return welfareGiftRecordMapper.selectWelfareGiftRecordById(id);
    }

    /**
     * 查询礼包发放详情列表
     *
     * @param welfareGiftRecord 礼包发放详情
     * @return 礼包发放详情
     */
    @Override
    public List<WelfareGiftRecord> selectWelfareGiftRecordList(WelfareGiftRecord welfareGiftRecord)
    {
        List<WelfareGiftRecord> welfareGiftRecords = welfareGiftRecordMapper.selectWelfareGiftRecordList(welfareGiftRecord);

        long nonNullCount = welfareGiftRecords.stream()
                .filter(Objects::nonNull)
                .count();

        if (nonNullCount > 0) {
            for (WelfareGiftRecord giftRecord : welfareGiftRecords) {
                WelfareGiftContent welfareGiftContent = welfareGiftContentService.selectWelfareGiftContentById(giftRecord.getGiftContentId());
                if (welfareGiftContent != null && StringUtils.isNotEmpty(welfareGiftContent.getContentName())) {
                    giftRecord.setGiftName(welfareGiftContent.getContentName());
                }
            }
        }
        return welfareGiftRecords;
    }

    @Override
    public List<WelfareGiftRecord> selectWelfareGiftRecordListGroup(WelfareGiftRecord welfareGiftRecord)
    {
        List<WelfareGiftRecord> welfareGiftRecords = welfareGiftRecordMapper.selectWelfareGiftRecordListGroup(welfareGiftRecord);
        if (welfareGiftRecords.size() > 0) {
            for (WelfareGiftRecord giftRecord : welfareGiftRecords) {
                WelfareGift welfareGift = welfareGiftService.selectWelfareGiftById(giftRecord.getGiftId());
                if (welfareGift != null && StringUtils.isNotEmpty(welfareGift.getName())) {
                    giftRecord.setGiftName(welfareGift.getName());
                }
            }
        }
        return welfareGiftRecords;
    }

    /**
     * 新增礼包发放详情
     *
     * @param welfareGiftRecord 礼包发放详情
     * @return 结果
     */
    @Override
    public int insertWelfareGiftRecord(WelfareGiftRecord welfareGiftRecord,List<Long> ids)
    {
        //查询礼包内容
        List<WelfareGiftContent> welfareGiftContents = welfareGiftContentService.selectWelfareGiftContentByGiftId(welfareGiftRecord.getGiftId());

        if (welfareGiftContents.size() < 1){
            throw new RuntimeException("礼包内容为空");
        }

        //转换结束时间
        welfareGiftRecord.setEndTime(DateUtils.toEndTime(welfareGiftRecord.getEndTimes()));

        for (Long id : ids) {

            //验证人员信息
            MemberUserInfo memberUserInfo = memberUserInfoService.selectMemberUserInfoById(id);
            if (memberUserInfo == null){
                throw new RuntimeException(id + "人员信息有误，发放失败！");
            }

//            int verify = memberUserInfoService.verifyGift(id);
//            if (verify > 0){
//                throw new RuntimeException(memberUserInfo.getName() + "已发放过礼包，不可重复发放！");
//            }

            welfareGiftRecord.setMemberId(id);
            welfareGiftRecord.setName(memberUserInfo.getName());
            welfareGiftRecord.setMemberNum(memberUserInfo.getMemberNum());
            welfareGiftRecord.setPhone(memberUserInfo.getPhone());
            welfareGiftRecord.setMemberType(memberUserInfo.getMemberType());
            welfareGiftRecord.setCreateTime(DateUtils.getNowDate());

            int i = 0;
            //礼包内容
            for (WelfareGiftContent welfareGiftContent : welfareGiftContents) {
                welfareGiftRecord.setGiftContentId(welfareGiftContent.getId());
                for (int j = 0; j < welfareGiftContent.getNum(); j++) {
                    i += welfareGiftRecordMapper.insertWelfareGiftRecord(welfareGiftRecord);
                }

            }

            if (i < 1) {
                throw new RuntimeException(memberUserInfo.getName() + "发放失败，请稍后重试");
            }

            //非业主会籍更新发放状态
            if (!"1".equals(memberUserInfo.getMemberType())) {
                MemberUserInfo memberUser = new MemberUserInfo();
                memberUser.setId(id);
                memberUser.setGiftStatus(1);
                memberUserInfoService.updateMemberUserInfo(memberUser);
            }

        }

        return 1;
    }

    /**
     * 修改礼包发放详情
     *
     * @param welfareGiftRecord 礼包发放详情
     * @return 结果
     */
    @Override
    public int updateWelfareGiftRecord(WelfareGiftRecord welfareGiftRecord)
    {
        welfareGiftRecord.setUpdateTime(DateUtils.getNowDate());
        return welfareGiftRecordMapper.updateWelfareGiftRecord(welfareGiftRecord);
    }

    /**
     * 批量删除礼包发放详情
     *
     * @param ids 需要删除的礼包发放详情主键
     * @return 结果
     */
    @Override
    public int deleteWelfareGiftRecordByIds(Long[] ids)
    {
        return welfareGiftRecordMapper.deleteWelfareGiftRecordByIds(ids);
    }

    /**
     * 删除礼包发放详情信息
     *
     * @param id 礼包发放详情主键
     * @return 结果
     */
    @Override
    public int deleteWelfareGiftRecordById(Long id)
    {
        return welfareGiftRecordMapper.deleteWelfareGiftRecordById(id);
    }

    @Override
    public int batchInsertGiftRecords(Long giftId, List<MemberUserInfo> users, String endTimes) {

        //查询礼包内容
        List<WelfareGiftContent> welfareGiftContents = welfareGiftContentService.selectWelfareGiftContentByGiftId(giftId);
        if (welfareGiftContents.size() < 1){
            throw new RuntimeException("礼包内容为空");
        }

        for (MemberUserInfo user : users) {
            //查询会员
            MemberUserInfo memberUserInfo = memberUserInfoService.selectMemberUserInfoByPhone(user.getPhone());
            if (memberUserInfo == null){
                throw new RuntimeException(user.getName() + "信息有误，发券失败！");
            }

            //验证发放状态
            WelfareGiftRecord record = new WelfareGiftRecord();
            record.setMemberId(memberUserInfo.getId());
//            int verify = memberUserInfoService.verifyGift(memberUserInfo.getId());
//            if (verify > 0){
//                throw new RuntimeException(user.getName() + "已发放过礼包，不可重复发放！");
//            }

            record.setGiftId(giftId);
            record.setMemberType(memberUserInfo.getMemberType());
            record.setName(user.getName());
            record.setPhone(user.getPhone());
            record.setEndTime(DateUtils.toEndTime(endTimes));
            record.setCreateBy(SecurityUtils.getUsername());
            record.setCreateTime(new Date());

            int i = 0;
            //礼包内容
            for (WelfareGiftContent welfareGiftContent : welfareGiftContents) {
                record.setGiftContentId(welfareGiftContent.getId());
                for (int j = 0; j < welfareGiftContent.getNum(); j++) {
                    i += welfareGiftRecordMapper.insertWelfareGiftRecord(record);
                }

            }

            if (i < 1) {
                throw new RuntimeException(user.getName() + "发放失败，请稍后重试");
            }

            //非业主会籍更新发放状态
            if (!"1".equals(memberUserInfo.getMemberType())) {
                MemberUserInfo memberUser = new MemberUserInfo();
                memberUser.setId(memberUserInfo.getId());
                memberUser.setGiftStatus(1);
                memberUserInfoService.updateMemberUserInfo(memberUser);
            }
        }
        return 0;

    }

    @Override
    public List<WelfareGiftRecord> selectUniWelfareGiftRecord(WelfareGiftRecord welfareGiftRecord) {
        return welfareGiftRecordMapper.selectUniWelfareGiftRecord(welfareGiftRecord);
    }

    @Override
    public List<ResultServe> selecResultGiftRecordList(WelfareGiftRecord welfareGiftRecord) {

        welfareGiftRecord.setStatus(0);
        //副卡则查询主卡的礼包
        if (welfareGiftRecord.getMemberId() != null){
            MemberUserInfo memberUserInfo = memberUserInfoService.selectMemberUserInfoById(welfareGiftRecord.getMemberId());
            if (memberUserInfo == null){
                MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectMemberSubCardInfoById(welfareGiftRecord.getMemberId());
                if (memberSubCardInfo != null) {
                    welfareGiftRecord.setMemberId(memberSubCardInfo.getMemberId());
                }
            }
        }

        List<WelfareGiftRecord> welfareGiftRecords = welfareGiftRecordMapper.selectWelfareGiftRecordListGroup(welfareGiftRecord);

        List<ResultServe> resultServes = new ArrayList<>();
        if (welfareGiftRecords.size() > 0){
            for (WelfareGiftRecord giftRecord : welfareGiftRecords) {
                //封装一级
                ResultServe resultServe = new ResultServe();
                resultServe.setId(String.valueOf(giftRecord.getGiftId()));
                resultServe.setLabel(welfareGiftService.selectWelfareGiftById(giftRecord.getGiftId()).getName());

                //封装二级
                welfareGiftRecord.setGiftId(giftRecord.getGiftId());
                welfareGiftRecord.setStatus(0);
                resultServe.setChildren(welfareGiftRecordMapper.selecResultGiftRecordList(welfareGiftRecord));
                resultServes.add(resultServe);
            }
        }

        return resultServes;
    }

    @Override
    public int updateWelfareGiftRecordStatus() {
        return welfareGiftRecordMapper.updateWelfareGiftRecordStatus();
    }

    @Override
    public int selectWelfareGiftRecordCount(Long giftId) {
        return welfareGiftRecordMapper.selectWelfareGiftRecordCount(giftId);
    }
}
